<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/mammoth@1.4.8/mammoth.browser.min.js"></script>
    <title>Word文档内容统计工具</title>
</head>
<style>
    body {
        font-family: Arial, sans-serif;
    }

    table {
        width: 100%;
        border-collapse: collapse;
    }

    th, td {
        border: 1px solid #ccc;
        padding: 8px;
        text-align: left;
    }

    th {
        background-color: #f2f2f2;
    }

</style>
<body>
<h1>Word文档内容统计工具</h1>
<input type="file" id="fileInput" multiple accept=".docx">
<div>
    <label for="tagInput">输入标记内容（多个用逗号分隔）：</label>
    <input type="text" id="tagInput">
</div>
<div id="result" style="display: none"></div>
<!--<div id="cleansing" style=""></div>-->
<button id="submitBtn">开始统计</button>
<table id="resultTable">
    <thead>
    <tr>
        <th>文件名</th>
        <th>标记</th>
        <th>标记内容</th>
    </tr>
    </thead>
    <tbody></tbody>
</table>
<script>
    window.onload = function () {
        // 设置默认值，以免重复输入
        document.getElementById("tagInput").value = "RT,CIE,LI,SDF,UN,PE,NP";
    }

    // 未解析版本 -> 错误
    function parseWordDocxFileOld(inputFile) {
        return new Promise((resolve, reject) => {
            var file = inputFile || [];

            // 计算大致时间，方便设置定时器
            // console.time();
            var reader = new FileReader();
            reader.onloadend = function (event) {
                var arrayBuffer = reader.result;

                mammoth.convertToHtml({arrayBuffer: arrayBuffer}).then(function (resultObject) {
                    document.getElementById("result").innerHTML = resultObject.value;
                })

                // 计算大致时间，方便设置定时器
                // console.timeEnd();

            };
        })
        reader.readAsArrayBuffer(file);
    }

    function parseWordDocxFile(inputFile) {
        return new Promise((resolve, reject) => {
            var file = inputFile || [];

            // 计算大致时间，方便设置定时器
            // console.time();
            var reader = new FileReader();
            reader.onload = function (event) {
                var arrayBuffer = event.target.result;

                mammoth.convertToHtml({arrayBuffer: arrayBuffer}).then(function (resultObject) {
                    document.getElementById("result").innerHTML = resultObject.value;
                    resolve(); // 添加 resolve() 以便在操作完成后解析 Promise
                })

                // 计算大致时间，方便设置定时器
                // console.timeEnd();
            };
            reader.readAsArrayBuffer(file);
        })
    }

    function delay(i, name, file, tags, resultTable) {
        // setTimeout(function () {
        let docToHTML = document.getElementById("result");
        // console.log(docToHTML);
        let htmlString = docToHTML.textContent;
        // console.log(htmlString);
        let textString = htmlString.replace(/<p>|<\/p>/g, '').trim();

        // 为第一个文件创建清洗数据后的 div
        var element = document.createElement('div');
        element.setAttribute('id', name);
        document.body.appendChild(element);
        document.getElementById(name).style.display = "none";
        document.getElementById(name).innerHTML = textString;

        // console.log(textString);

        // 遍历标记内容
        tags.forEach(tag => {
            const tagContents = document.getElementById(name).querySelectorAll(tag);

            // 添加结果到表格
            tagContents.forEach(content => {
                const row = resultTable.insertRow();
                row.insertCell().textContent = file.name;
                row.insertCell().textContent = tag;
                row.insertCell().textContent = content.textContent;
            });
        });

        // 清除转职中转 div 中的内容
        document.getElementById("result").innerHTML = "";
        // }, 10);
    }

    document.getElementById('submitBtn').addEventListener('click', function () {
        const fileInput = document.getElementById('fileInput');
        const tagInput = document.getElementById('tagInput');
        const resultTable = document.getElementById('resultTable').getElementsByTagName('tbody')[0];

        // 清空表格内容
        resultTable.innerHTML = '';

        // 获取文件和标记内容
        const files = fileInput.files;
        const tags = tagInput.value.split(',').map(tag => tag.trim());

        // 遍历文件
        for (let i = 0; i < files.length; i++) {
            let name = "cleansing" + i;
            const file = files[i];
            parseWordDocxFile(file).then(() => {
                delay(i, name, file, tags, resultTable);
            }).catch((error) => {
                console.error("Error parsing file:", error);
            });
            // parseWordDocxFile(file);
            // setTimeout(function () {
            //     delay(i, name, file, tags, resultTable);
            // }, 10);
            // var element = document.getElementById(name);
            // element.parentNode.removeChild(element);
        }

        reader.readAsText(file);

    });

</script>
</body>
</html>
